package com.lin.config;

import com.lin.filter.MyLoginFilter;
import com.lin.filter.MyOncePerRequestFilter;
import com.lin.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * 时间：2023/8/20
 */
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {



    @Resource
    private UserService userService;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public MyLoginFilter myLoginFilter() throws Exception {
        MyLoginFilter myLoginFilter = new MyLoginFilter();
        //配置认证管理器
        myLoginFilter.setAuthenticationManager(authenticationManagerBean());
        //配置认证成功和失败处理
        myLoginFilter.setAuthenticationSuccessHandler(new LoginSuccessHandler());
        myLoginFilter.setAuthenticationFailureHandler(new LoginFailHandler());
        myLoginFilter.setKaptchaParameter("kaptcha");
        return myLoginFilter;
    }

    @Bean
    public MyOncePerRequestFilter myOncePerRequestFilter(){
        MyOncePerRequestFilter myOncePerRequestFilter = new MyOncePerRequestFilter();
        return myOncePerRequestFilter;
    }



    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/login").permitAll()
                .mvcMatchers("/vc.png").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .logout()
                .logoutSuccessHandler(new MyLogoutSuccessHandler())
                .and()
                .csrf().disable();

        http.addFilterAt(myLoginFilter(), UsernamePasswordAuthenticationFilter.class);
        http.addFilterBefore(myOncePerRequestFilter(),UsernamePasswordAuthenticationFilter.class);
    }

}
